﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using AvaloniaApplicationDemo.IServices;
using AvaloniaApplicationDemo.Models;
using AvaloniaApplicationDemo.Util;

namespace AvaloniaApplicationDemo.Services;

public class ConfigCSVManager : IConfigCSVManager
{
    /// <summary>
    /// 从CSV文件导入寄存器映射关系
    /// </summary>
    /// <param name="filePath">CSV文件路径</param>
    /// <param name="deviceModel">设备模型</param>
    /// <returns>是否导入成功</returns>
    public bool ImportRegisterMappingsFromCsv(string filePath, DeviceModel deviceModel)
    {
        try
        {
            // 清空现有映射
            deviceModel.RegisterMappings.Clear();

            using (var reader = new StreamReader(filePath))
            {
                // 跳过标题行
                reader.ReadLine();

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    var parts = line.Split(',');
                    if (parts.Length >= 2 && ushort.TryParse(parts[0].Trim(), out var address))
                    {
                        var alias = parts[1].Trim();
                        deviceModel.RegisterMappings[address] = alias;
                    }
                }
            }

            return deviceModel.RegisterMappings.Count > 0;
        }
        catch (Exception ex)
        {
            AppLogger.Error(ex, "导入CSV寄存器映射失败");
            return false;
        }
    }

    /// <summary>
    /// 导出CSV配置模板
    /// </summary>
    /// <param name="filePath">导出文件路径</param>
    /// <param name="deviceModel">设备模型</param>
    /// <returns>是否导出成功</returns>
    public bool ExportConfigTemplate(string filePath, Dictionary<ushort, string> registerMappings)
    {
        try
        {
            using (var writer = new StreamWriter(filePath))
            {
                writer.WriteLine("地址,别名");
                foreach (var kvp in registerMappings) writer.WriteLine($"{kvp.Key},{kvp.Value}");
            }

            return true;
        }
        catch (Exception ex)
        {
            AppLogger.Error(ex, "导出CSV配置模板失败");
            return false;
        }
    }
}